package com.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Random;

import com.beans.*;

public class TableModel extends ModelDAO
{
	Connection connection = null;
	ResultSet resultSet = null; 

	/**
	 * Get a random place number 
	 * @param places : contains the places busied
	 */
	public int getRandomPlace (ArrayList<Integer> places)
	{
		Random r = new Random();
		int valeurMin = 0;
		int valeurMax = 9;
		int valeur;
		
		valeur = valeurMin + r.nextInt(valeurMax - valeurMin);
		
		for(int i=0; i<10; i++)
		{
			if (valeur == places.get(i))
			{
				valeur = valeurMin + r.nextInt(valeurMax - valeurMin);
			}
		}
		return valeur;
	}
	
	/**
	 * Add a table in the database
	 */
	public int addTable(){

		PreparedStatement prepStat = null;
		String query = null;
		int valErreur = 0;

		try
		{
			connection = super.getConnection();
			query = "INSERT INTO room (ro_name) VALUES (?)";
			prepStat = connection.prepareStatement(query);

			prepStat.setString(1, Table.getRandomName());			

			// Execute the request
			valErreur = prepStat.executeUpdate();
			
			resultSet = prepStat.getGeneratedKeys(); 
			if ( resultSet != null && resultSet.next() ) 
			{ 
				// Get the last ID insert
			    valErreur = resultSet.getInt(1); 
			}
		}
		catch(Exception ex)
		{
			valErreur = 0;
			System.out.println("Table - Insertion impossible");
			ex.printStackTrace();
		}

		try{
			prepStat.close();
			connection.close();
		}catch(Exception ex){
			ex.printStackTrace();
		}

		return valErreur;
	}
	
	/**
	 * Join a specified table
	 * @param tableId : the table we want to join
	 * @param userId : the user who join
	 */
	public boolean joinTable(long tableId, long userId)
	{
		PreparedStatement prepStat = null;
		String query = null;
		
		// TODO : generate random places !!!

		try 
		{
			ArrayList<Integer> places = new ArrayList<Integer>();
			int place = 0;
			connection = super.getConnection();
			query = "SELECT roo_place FROM room_on WHERE ro_id=?";
			prepStat = connection.prepareStatement(query);
			prepStat.setLong(1, tableId);
			
			if (resultSet!=null){
				while (resultSet.next()){
					places.add(resultSet.getInt("roo_place"));
				}
			}
			place = getRandomPlace(places);
			System.out.println("Place en cours : " + place);
		
			query = "INSERT INTO room_on (u_id, ro_id, roo_place) VALUES (?,?,?)";
			prepStat = connection.prepareStatement(query);

			prepStat.setLong(1, userId);			
			prepStat.setLong(2, tableId);		
			prepStat.setInt(3, place);
			
			return true;
		}
		catch(Exception ex)
		{
			System.out.println("Table - Jointure impossible");
			ex.printStackTrace();
		}

		try
		{
			prepStat.close();
			connection.close();
		}catch(Exception ex){
			ex.printStackTrace();
		}

		return false;
	}
	
	
	/**
	 * Get the 10 last tables with some players
	 */
	public ArrayList<Table> getLastTables(){
		PreparedStatement prepStat = null;
		ArrayList<Table> allTables = new ArrayList<Table>();
		String query = null;

		try{
			connection = super.getConnection();
			query = "SELECT r.*, u.COUNT(*) AS count FROM room r" +
					" INNER JOIN room_on ro ON ro.ro_id = r.ro_id" +
					" INNER JOIN users u ON u.u_id = ro.u_id" + 
					" INNER JOIN users_log l ON l.u_id = u.u_id AND l.log_statut = 1"+
					" ORDER BY r.r_date DESC LIMIT 5";
			
			// Pour tester
			query = "SELECT * FROM room ORDER BY ro_date LIMIT 5";
			prepStat = connection.prepareStatement(query);
			resultSet = prepStat.executeQuery();

			if (resultSet!=null){
				while(resultSet.next()){
					Table table = new Table();
					table.setName(resultSet.getString("ro_name"));
					table.setCount(resultSet.getInt("ro_id"));
					table.setTableId(resultSet.getInt("ro_id"));
					allTables.add(table);
				}
			}

		} catch(Exception ex){
			System.out.println("Erreur de requete " + ex);
		}

		try
		{
			resultSet.close();
			prepStat.close();
			connection.close();
		} catch(Exception ex){
			ex.printStackTrace();
		}

		return allTables;
	}
	
}